package com.alfy.websocketdemo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.CloseReason;
import javax.websocket.Session;
import java.io.IOException;
import java.nio.ByteBuffer;

@WebServlet(urlPatterns = "/ws")
public class WsServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String oper = req.getParameter("oper");
        if ("client".equals(oper)) {
            try {
                WebSocketClient webSocketClient = new WebSocketClient();
                webSocketClient.connect("ws://localhost:8889/websocket/java_client?name=qwe&age=12333&auth=valid-token");
                Session session = webSocketClient.session;
                session.getBasicRemote().sendText("Java 客户端字符串消息");
                session.getBasicRemote().sendBinary(ByteBuffer.wrap("Java 客户端二进制消息".getBytes()));
                CloseReason closeReason = new CloseReason(CloseReason.CloseCodes.RESERVED, "手动关闭");
                session.close(closeReason);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            resp.getWriter().write("success");
        }else if ("sysi".equals(oper)) {
            for (WebSocketServer myWebSocketEndpoint : WebSocketServer.getConnections()) {
                myWebSocketEndpoint.getSession().getBasicRemote().sendText("本次消息是系统消息, 各位用户大家好");
            }
            resp.getWriter().write("system info success");
        }else {
            //...
        }
    }

}
